package utils

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"awesomeProject/pkg/errors"
)

// 从上下文获取用户ID
func GetUserIDFromContext(c *gin.Context) uint {
	userID, exists := c.Get("user_id")
	if !exists {
		return 0
	}
	return userID.(uint)
}

// 统一错误处理
func HandleError(c *gin.Context, err error) {
	if appErr, ok := err.(*errors.AppError); ok {
		statusCode := appErr.GetHTTPStatus()
		c.JSON(statusCode, gin.H{
			"error": appErr.Message,
			"code":  appErr.Code,
		})
	} else {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Internal server error",
			"code":  errors.InternalError,
		})
	}
}

// 成功响应
func SuccessResponse(c *gin.Context, data interface{}) {
	c.JSON(http.StatusOK, gin.H{
		"code":    "SUCCESS",
		"message": "Operation successful",
		"data":    data,
	})
}

// 分页响应
func PaginatedResponse(c *gin.Context, data interface{}, total int64, page, limit int) {
	c.JSON(http.StatusOK, gin.H{
		"code":    "SUCCESS",
		"message": "Operation successful",
		"data":    data,
		"total":   total,
		"page":    page,
		"limit":   limit,
	})
}